# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: yuxuan

import os
import json
import re


def clean_json(string):
  string = re.sub(r'#.*$', '', string, flags=re.M)
  string = re.sub(r'//.*$', '', string, flags=re.M)
  string = re.sub(",[ \t\r\n]+}", "}", string)
  string = re.sub(",[ \t\r\n]+]", "]", string)
  return string


def get_reference_trade_futures_type(config):
  product0 = list(config['products0'].keys())[0]
  product1 = list(config['products1'].keys())[0]
  type0 = product0.split('.')[-1] if '.' in product0 else 'Spot'
  type1 = product1.split('.')[-1] if '.' in product1 else 'Spot'
  return type0, type1


def get_strategy_config_from_script(coin_deploy_repo, script_name, is_coin2=False):
  configs = []
  flags = {}
  if not is_coin2:
    found = False
    with open(f'{coin_deploy_repo}/basis_strat/{script_name}') as fi:
      for line in fi.readlines():
        line = line.strip()
        if line.startswith('--'):
          if '=' in line:
            key, val = line.split('=')
          else:
            key, val = line.split(' ', 1)
          key = key.strip()[2:]
          val = val[:-1].strip() or '1'
          if key != 'config_filename':
            flags[key] = val

        if '--config_filename' in line:
          found = True
        elif '2>&1' in line:
          break
        else:
          if found:
            configs.append(line)
    configs = '{%s}' % ' '.join(configs)
    configs = json.loads(clean_json(configs))
  else:
    config_path = f'{coin_deploy_repo}/basis_strat2/config/{script_name}.json'
    if os.path.exists(config_path):
      with open(config_path, 'r') as fi:
        configs = json.load(fi)
  return configs, flags
